package com.smart.thirteen.rowcallbackHandler;

import com.smart.thirteen.Topic;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author junrui.wang
 * @create 2019/10/21
 */
public class RowCallbackHandlerTest {
    public static void main(String[] args) {
        ApplicationContext ac = new ClassPathXmlApplicationContext("classpath*:com/smart/thirteen/applicationContext-template.xml");
        JdbcTemplate jdbcTemplate = (JdbcTemplate) ac.getBean("jdbcTemplate");
        final int id = 1;
        final Topic topic = new Topic();

        String sql = "SELECT topic_title, user_id FROM t_topic WHERE id=?";
        jdbcTemplate.query(sql, new Object[]{id}, new RowCallbackHandler() {
            @Override
            public void processRow(ResultSet rs) throws SQLException {
                topic.setId(id);
                topic.setTopic_title(rs.getString(1));
                topic.setUser_id(rs.getString(2));
            }
        });

        System.out.println(topic);

        //处理多条数据集
        final List<Topic> topics = new ArrayList<>();
        String sql2 = "SELECT id, topic_title, user_id FROM t_topic WHERE id BETWEEN ? AND ?";
        jdbcTemplate.query(sql2, new Object[]{1, 3}, new RowCallbackHandler() {
            @Override
            public void processRow(ResultSet rs) throws SQLException {
                Topic topic1 = new Topic();
                topic1.setId(rs.getInt(1));
                topic1.setTopic_title(rs.getString(2));
                topic1.setUser_id(rs.getString(3));
                topics.add(topic1);
            }
        });

        System.out.println(topics);



    }
}
